package com.example.jpatest.service.impl;

import com.example.jpatest.entity.*;
import com.example.jpatest.repository.EnterRepository;
import com.example.jpatest.repository.WinRepository;
import com.example.jpatest.service.EnterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class EnterServiceImpl implements EnterService {

    @Autowired
    EnterRepository enterRepository;

    @Autowired
    WinRepository winRepository;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void enter(Team team,Competition competition) {
        Enter enter = new Enter();
        enter.setTeam(team);
        enter.setCompetition(competition);
        enterRepository.save(enter);
    }

    @Override
    public List<Enter> getEnters() {
        return enterRepository.findAll();
    }

    @Override
    public Enter getEnter(Team team,Competition competition) {
        return enterRepository.findByCompetitionAndTeam(competition,team).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void cancelEnter(Team team, Competition competition) {
        Enter enter = enterRepository.findByCompetitionAndTeam(competition, team).orElse(null);
        team.getEnter().remove(enter);
        competition.getEnters().remove(enter);
        enterRepository.delete(enter);
    }

    @Override
    public Enter getById(Long id) {
        return enterRepository.findById(id).orElse(null);
    }

    @Override
    public Win getWinInfo(Enter enter) {
        return enter.getWin();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveEnter(Enter enter) {
        enterRepository.save(enter);
    }
}
